package cn.edu.sdju.fengguoyu.ahoedgemonitor;

import cn.edu.sdju.fengguoyu.logger.Logger;
import cn.edu.sdju.fengguoyu.proto.*;
import cn.edu.sdju.fengguoyu.util.AhoUtil;
import io.grpc.ManagedChannel;
import io.grpc.ManagedChannelBuilder;
import io.grpc.stub.StreamObserver;

public class RPCThread implements Runnable {
    Logger logger = new Logger(RPCThread.class);
    private final ManagedChannel channel;
    public String ipAddress;
    public int port;
    public RPCThread(String address, int port) {
        this.ipAddress  = address;
        this.port  = port;
        channel = ManagedChannelBuilder.forAddress(address, port).usePlaintext().build();
    }
    @Override
    public void run() {

    }

    public void registerObserver() {
        RegisterServiceGrpc.RegisterServiceStub serviceStub = RegisterServiceGrpc.newStub(this.channel);
        logger.log(String.format("Call back address:%s:2339", App.localIPv4Address));
        serviceStub.registerObserver(ObserverInfo.newBuilder().setIpAddress(App.localIPv4Address).setPort(2339).build(), new StreamObserver<Response>() {
            @Override
            public void onNext(Response response) {
                App.getApp().id = response.getUserId();
                logger.log(String.format("got id:%d",App.getApp().id));
            }

            @Override
            public void onError(Throwable throwable) {

            }

            @Override
            public void onCompleted() {

            }
        });
    }
    public void disconnect() {
        RegisterServiceGrpc.RegisterServiceStub serviceStub = RegisterServiceGrpc.newStub(this.channel);
        serviceStub.unregisterObserver(UnregisterObserverRequest.newBuilder().setId(App.getApp().id).build(), new StreamObserver<Response>() {
            @Override
            public void onNext(Response response) {

            }

            @Override
            public void onError(Throwable throwable) {

            }

            @Override
            public void onCompleted() {
                logger.log("Disconnected");
            }
        });
    }

    public void getServerList(String named, StreamObserver<ServicesDetailList> servicesListStreamObserver) {
        RegisterServiceGrpc.RegisterServiceStub serviceStub = RegisterServiceGrpc.newStub(this.channel);
        serviceStub.queryServiceDetail(QueryRequest.newBuilder().setServiceName(named).build(), servicesListStreamObserver);
    }
}
